<template>
  <div class="user-manage">
    <t-card title="用户管理">
      <!-- 搜索区域 -->
      <div class="search-area">
        <t-input v-model="searchKeyword" placeholder="请输入姓名/手机/账号搜索" clearable style="width: 300px">
          <template #suffix>
            <t-icon name="search" @click="handleSearch" />
          </template>
        </t-input>
        <t-select v-model="statusFilter" placeholder="状态筛选" clearable style="width: 120px">
          <t-option key="all" label="全部" value="all" />
          <t-option key="active" label="已激活" value="active" />
          <t-option key="inactive" label="已禁用" value="inactive" />
        </t-select>
        <t-button theme="primary" @click="handleSearch">搜索</t-button>
        <t-button theme="default" @click="handleReset">重置</t-button>
      </div>

      <t-table :data="slicedData" :columns="columns" :hover="true" :loading="false" :pagination="pagination"
        @page-change="onPageChange" row-key="id">
        <template #isActive="{ row }">
          <t-tag :theme="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '已激活' : '已禁用' }}
          </t-tag>
        </template>
        <template #op="{ row }">
          <t-space>
            <t-button :theme="row.isActive ? 'danger' : 'success'" variant="text" @click="toggleUserStatus(row)">
              {{ row.isActive ? '禁用' : '激活' }}
            </t-button>
            <t-dropdown :options="moreActions" @click="handleMoreAction($event, row)">
              <t-button variant="text">
                更多
                <template #suffix>
                  <t-icon name="chevron-down" />
                </template>
              </t-button>
            </t-dropdown>
          </t-space>
        </template>
      </t-table>
    </t-card>
    
    <!-- 用户详情/编辑弹出层 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="isEditMode ? '编辑用户' : '用户详情'"
      :width="680"
      :footer="isEditMode"
      :on-confirm="handleSaveUser"
      :on-close="closeDialog"
      attach="body"
    >
      <template v-if="currentUser">
        <t-form
          ref="userForm"
          :data="userFormData"
          :disabled="!isEditMode"
          :label-width="100"
        >
          <t-form-item label="姓名" name="name">
            <t-input v-model="userFormData.name" placeholder="请输入姓名" />
          </t-form-item>
          <t-form-item label="电话" name="phone">
            <t-input v-model="userFormData.phone" placeholder="请输入电话" />
          </t-form-item>
          <t-form-item label="邮箱" name="email">
            <t-input v-model="userFormData.email" placeholder="请输入邮箱" />
          </t-form-item>
          <t-form-item label="账号" name="account">
            <t-input v-model="userFormData.account" placeholder="请输入账号" />
          </t-form-item>
          <t-form-item label="状态" name="isActive">
            <t-radio-group v-model="userFormData.isActive">
              <t-radio :value="true">已激活</t-radio>
              <t-radio :value="false">已禁用</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item v-if="!isEditMode" label="创建时间">
            <span>{{ currentUser.createdAt }}</span>
          </t-form-item>
          <t-form-item v-if="!isEditMode" label="最后登录IP">
            <span>{{ currentUser.lastLoginIp }}</span>
          </t-form-item>
          <t-form-item v-if="!isEditMode" label="最后登录时间">
            <span>{{ currentUser.lastLoginAt }}</span>
          </t-form-item>
        </t-form>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, reactive } from 'vue'
  import { 
    MessagePlugin, 
    DialogPlugin, 
    Select as TSelect, 
    Option as TOption,
    Dialog as TDialog,
    Form as TForm,
    FormItem as TFormItem,
    Input as TInput,
    RadioGroup as TRadioGroup,
    Radio as TRadio
  } from 'tdesign-vue-next'
  import type { UserData } from '../types'

  // 搜索关键词
  const searchKeyword = ref('')
  
  // 状态筛选
  const statusFilter = ref<'all' | 'active' | 'inactive'>('all')

  // 模拟数据
  const userData = ref<UserData[]>([
    {
      id: 1,
      name: '张三',
      phone: '13800138000',
      email: 'zhangsan@example.com',
      account: 'zhangsan',
      createdAt: '2023-01-01 08:00:00',
      lastLoginIp: '192.168.1.1',
      lastLoginAt: '2024-01-10 15:30:00',
      isActive: true
    },
    {
      id: 2,
      name: '李四',
      phone: '13800138001',
      email: 'lisi@example.com',
      account: 'lisi',
      createdAt: '2023-02-01 09:00:00',
      lastLoginIp: '192.168.1.2',
      lastLoginAt: '2024-01-09 14:20:00',
      isActive: true
    },
    {
      id: 3,
      name: '王五',
      phone: '13800138002',
      email: 'wangwu@example.com',
      account: 'wangwu',
      createdAt: '2023-03-01 10:00:00',
      lastLoginIp: '192.168.1.3',
      lastLoginAt: '2024-01-08 16:45:00',
      isActive: false
    }
  ])

  // 表格列配置
  const columns = [
    { colKey: 'name', title: '姓名', minWidth: 80 },
    { colKey: 'phone', title: '电话', minWidth: 120 },
    { colKey: 'email', title: '邮箱', minWidth: 180 },
    { colKey: 'account', title: '账号', minWidth: 100 },
    { colKey: 'createdAt', title: '创建时间', minWidth: 160 },
    { colKey: 'lastLoginIp', title: '登录IP', minWidth: 120 },
    { colKey: 'lastLoginAt', title: '最后登录时间', minWidth: 160 },
    { colKey: 'isActive', title: '状态', minWidth: 80 },
    { colKey: 'op', title: '操作', minWidth: 120 }
  ]

  // 根据关键词和状态过滤数据
  const filteredData = computed(() => {
    let result = userData.value
    
    // 关键词筛选
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      result = result.filter(user =>
        user.name.toLowerCase().includes(keyword) ||
        user.phone?.includes(keyword) ||
        user.account?.toLowerCase().includes(keyword)
      )
    }
    
    // 状态筛选
    if (statusFilter.value !== 'all') {
      const isActive = statusFilter.value === 'active'
      result = result.filter(user => user.isActive === isActive)
    }
    
    return result
  })

  // 分页配置
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: computed(() => filteredData.value.length),
    showJumper: true,
    showPageSize: true
  })

  // 计算当前页数据
  const slicedData = computed(() => {
    const start = (pagination.value.current - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    return filteredData.value.slice(start, end)
  })

  // 搜索处理
  const handleSearch = () => {
    pagination.value.current = 1 // 搜索时重置到第一页
  }

  // 重置搜索
  const handleReset = () => {
    searchKeyword.value = ''
    statusFilter.value = 'all'
    pagination.value.current = 1
  }

  // 更多操作选项类型定义
  interface MoreAction {
    content: string
    value: 'detail' | 'edit' | 'reset'
  }

  // 更多操作选项
  const moreActions: MoreAction[] = [
    { content: '查看详情', value: 'detail' },
    { content: '编辑信息', value: 'edit' },
    { content: '重置密码', value: 'reset' }
  ]

  // 页码改变处理
  const onPageChange = (current: number) => {
    pagination.value.current = current
  }

  // 当前操作的用户
  const currentUser = ref<UserData | null>(null)
  
  // 弹出层控制
  const dialogVisible = ref(false)
  const isEditMode = ref(false)
  const userFormData = reactive({
    name: '',
    phone: '',
    email: '',
    account: '',
    isActive: true
  })
  
  // 打开用户详情
  const openUserDetail = (user: UserData) => {
    currentUser.value = user
    isEditMode.value = false
    // 复制用户数据到表单
    Object.assign(userFormData, {
      name: user.name,
      phone: user.phone,
      email: user.email,
      account: user.account,
      isActive: user.isActive
    })
    dialogVisible.value = true
  }
  
  // 打开编辑用户
  const openUserEdit = (user: UserData) => {
    currentUser.value = user
    isEditMode.value = true
    // 复制用户数据到表单
    Object.assign(userFormData, {
      name: user.name,
      phone: user.phone,
      email: user.email,
      account: user.account,
      isActive: user.isActive
    })
    dialogVisible.value = true
  }
  
  // 关闭弹出层
  const closeDialog = () => {
    dialogVisible.value = false
    currentUser.value = null
  }
  
  // 保存用户信息
  const handleSaveUser = () => {
    if (!currentUser.value) return
    
    // 模拟保存操作
    const userIndex = userData.value.findIndex(u => u.id === currentUser.value!.id)
    if (userIndex !== -1) {
      // 更新用户数据
      userData.value[userIndex] = {
        ...userData.value[userIndex],
        name: userFormData.name,
        phone: userFormData.phone,
        email: userFormData.email,
        account: userFormData.account,
        isActive: userFormData.isActive
      }
      
      MessagePlugin.success('用户信息保存成功')
      dialogVisible.value = false
    }
  }

  // 切换用户状态
  const toggleUserStatus = (row: UserData) => {
    currentUser.value = row

    // 显示确认对话框
    let dialog = DialogPlugin.confirm({
      header: `确认${row.isActive ? '禁用' : '激活'}用户`,
      body: `您确定要${row.isActive ? '禁用' : '激活'}用户"${row.name}"吗？`,
      confirmBtn: {
        theme: row.isActive ? 'danger' : 'primary',
        content: '确认',
      },
      cancelBtn: '取消',
      onConfirm: () => {
        // 确认后执行状态切换
        const user = userData.value.find(u => u.id === row.id)
        if (user) {
          user.isActive = !user.isActive
          MessagePlugin.success(`已${user.isActive ? '激活' : '禁用'}用户：${user.name}`)
          dialog.destroy()
        }
      },
      onClose: () => {
        currentUser.value = null
        dialog.destroy()
      }
    })
  }

  // 处理更多操作
  const handleMoreAction = (option: MoreAction, row: UserData) => {
    switch (option.value) {
      case 'detail':
        openUserDetail(row)
        break
      case 'edit':
        openUserEdit(row)
        break
      case 'reset':
        MessagePlugin.info(`重置用户密码：${row.name}`)
        break
    }
  }
</script>

<style scoped>
  .user-manage {
    width: 100%;
    overflow-x: hidden;
  }

  .search-area {
    margin-bottom: 16px;
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap; /* 在空间不足时换行 */
  }

  .t-button {
    margin-left: 8px;
  }

  :deep(.t-table) {
    width: 100%;
  }

  :deep(.t-table__content) {
    width: 100%;
  }
</style>